import 'dart:io';

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

/// 视频播放
class CustomVideoPlayer extends StatefulWidget {
  final String videoUrl;
  final bool isLocalFile;

  const CustomVideoPlayer(this.videoUrl, {Key key, this.isLocalFile = false})
      : super(key: key);

  @override
  _VideoPlayerState createState() => _VideoPlayerState();
}

class _VideoPlayerState extends State<CustomVideoPlayer> {
  VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    if (widget.isLocalFile) {
      _controller = VideoPlayerController.file(File(widget.videoUrl))
        ..initialize().then((value) {
          setState(() {});
        });
    } else {
      _controller = VideoPlayerController.network(widget.videoUrl)
        ..initialize().then((_) {
          // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
          setState(() {});
        });
    }
    _controller.setLooping(true);
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Stack(
          alignment: Alignment.center,
          children: [
            _controller.value.isInitialized
                ? AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: VideoPlayer(_controller),
                  )
                : Container(),
            Positioned(
              child: InkWell(
                child: Image.asset(
                  _controller.value.isPlaying
                      ? 'assets/images/ic_pause.png'
                      : 'assets/images/ic_play.png',
                  width: 60,
                  height: 60,
                  color: Colors.white,
                ),
                onTap: () {
                  setState(() {
                    _controller.value.isPlaying
                        ? _controller.pause()
                        : _controller.play();
                  });
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
